<?php
namespace frontend\controllers;
use yii\web\Controller;
use frontend\models\VisitorCount;

class DownloadController extends Controller
{
    public function actionDownloadApp()
    {
        $ip=$this->get_ip();
        $agent=$_SERVER['HTTP_USER_AGENT'];
        if (strpos($agent, 'iPhone')||strpos($agent, 'iPad'))
        {
            return $this->redirect("https://itunes.apple.com/cn/app/guo-jia-jia/id1059334813?mt=8");
        }
        else
        {   //(strpos($agent, 'Android')||strpos($agent, 'Linux'))
            $recCount=VisitorCount::find()->where(['access_type'=>1,'ip'=>$ip])->count();
            if ($recCount>0)
            {
                $rec=VisitorCount::findOne(['access_type'=>1,'ip'=>$ip]);
                $rec->count=$rec->count+1;
                $rec->save();
            }
            else 
            {
                $rec=new VisitorCount();
                $rec->ip=$ip;
                $rec->count=1;
                $rec->time=date("Y-m-d H:i:s");
                $rec->access_type=1;
                $rec->save();
            }
            return $this->redirect("https://app.jajahome.com/furniture/Android/download/jajahome.apk");
        }
    }
    
    private function get_ip() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ips = explode(',', $_SERVER['HTTP_CLIENT_IP']);
            foreach ($ips as $ip) {
                $ip = trim($ip);
                if ($this->_validIP($ip) && !$this->_isPrivate($ip))
                    return $ip;
            }
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($ips as $ip) {
                $ip = trim($ip);
                if ($this->_validIP($ip) && !$this->_isPrivate($ip))
                    return $ip;
            }
        }
        return $_SERVER['REMOTE_ADDR'];
    }
    private function _validIP($ip) {
        $i = explode('.', $ip);
        if (count($i) != 4)
            return false;
            foreach ($i as $v) {
                if ($v < 0 || $v > 255)
                    return false;
            }
            return true;
    }
    
    private function _isPrivate($ip) {
        $i = explode('.', $ip);
        if ($i[0] == 10)
            return true;
            if ($i[0] == 172 && $i[1] > 15 && $i[1] < 32)
                return true;
                if ($i[0] == 192 && $i[1] == 168)
                    return true;
                    return false;
    }
}